/**
 * Created by zhoulin on 2019/3/31.
 */

$(function() {
  //查询菜单模块
  //ajax(0)
});
var schoolMap = new Map();
var app = new Vue({
  el: "#wrapper",
  data: {
    iframeSrc: "home1.html",
    toggleIndex: 0,
    companyText: "切换机构单位",
    userInfo: { username: "", nickname: "" },
    menuList: [
      {
        id: "1",
        icon: "fa fa-refresh",
        name: "系统权限加载中",
        pid: "0",
        url: "../login.html",
        children: []
      }
    ],
    companyList: [{ id: "1", name: "机构加载中" }],
    deptPermList: [
      { id: "1", type: "1", name: "二级单位加载中", schoolId: "0" }
    ],
    messageList: [],
    flagmsg: false
  },
  //进入页面初始化方法
  created: function() {
    this.getBackMessage();
    var that = this;
    var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
    if (empty(token)) {
      layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {
        time: 1500,
        icon: 5
      });
      setTimeout(function() {
        window.location.href = _LOGIN_PAGE;
      }, 1200);

      return;
    }

    //查询登录人信息
    that.getUserInfo();
    //初始化机构查询
    that.getCompanyInfo(0);
  },
  methods: {
    // 修改密码
    updateWp: function() {
      layer.open({
        type: 1,
        title: "修改密码",
        area: ["500px", "300px"],
        content: $("#updatePasswd")
      });
    },
    // 查询今天待回访
    getListToday: function() {
      var that = this;
      var companyId = sessionStorageUtils.getJson(
        storageKey.sessionStorageKey.companyId
      );
      Get(
        that,
        _HOST +
          _API.user_orderTrackRelation_getListToday +
          "?companyId=" +
          companyId,
        "",
        true
      ).then(function(response) {
        // 响应成功回调
        console.log(response);
        if (response) {
          if (response.success) {
            var list = response.list;
            if (!empty(list) && list.length > 0) {
              var message = {};
              message.content =
                "【顾客回访】今天有" + list.length + "位顾客待回访！";
              message.jumpLink = "./content-manage/member/visit/list.html";
              message.classS = 3;
              var lists = that.messageList;
              lists.push(message);
              that.messageList = lists;
              console.log(that.messageList);
            }
          } else {
            layer.msg(response.msg, { time: 1500, icon: 5 });
          }
        }
      });
    },
    // 查询消息
    getBackMessage: function() {
      var that = this;
      var companyId = sessionStorageUtils.getJson(
        storageKey.sessionStorageKey.companyId
      );
      Get(
        that,
        _HOST + _API.user_message_backMessage + "?companyId=" + companyId,
        "",
        true
      ).then(function(response) {
        // 响应成功回调
        console.log("查询浏览消息", response);
        if (response) {
          if (response.success) {
            var list = response.list;
            if (!empty(list) && list.length > 0) {
              var lists = that.messageList;
              lists = lists.concat(list);
              that.messageList = lists;
              console.log(that.messageList);
            }
          } else {
            layer.msg(response.msg, { time: 1500, icon: 5 });
          }
        }
      });
    },
    // 跳转
    toDetail: function(item) {
      console.log("点击");
      var that = this;
      var companyId = sessionStorageUtils.getJson(
        storageKey.sessionStorageKey.companyId
      );
      var name = "";
      if (item.classS == 1) {
        name = "客户商品浏览";
      } else if (item.classS == 2) {
        name = "音响圈管理";
      } else if (item.classS == 3) {
        name = "待回访管理";
      }
      if (item.classS == 1 || item.classS == 2) {
        Get(
          that,
          _HOST +
            _API.user_message_backMessageMark +
            "?companyId=" +
            companyId +
            "&type=" +
            item.classS
        ).then(function(response) {
          // 响应成功回调
          console.log("点消息成功后点消息成功后", item.jumpLink);
          that.messageList = [];
          setTimeout(createTab(item.jumpLink, name), 200);
        });
      } else {
        setTimeout(createTab(item.jumpLink, name), 200);
      }
    },
    // 确定
    submitPwd: function() {
      var that = this;
      var oldPassword = $('input[name="oldPassword"]').val();
      if (empty(oldPassword)) {
        layer.msg("请输入原始密码", { time: 1500, icon: 5 });
        return;
      }
      var password = $('input[name="password"]').val();
      if (empty(password)) {
        layer.msg("请输入新的密码", { time: 1500, icon: 5 });
        return;
      }
      var confirmPassword = $('input[name="confirmPassword"]').val();
      if (empty(confirmPassword)) {
        layer.msg("请输入确认密码", { time: 1500, icon: 5 });
        return;
      }
      if (password != confirmPassword) {
        layer.msg("新密码与确认密码不匹配！", { time: 1500, icon: 5 });
        return;
      }
      Post(
        that,
        _HOST +
          _API.business_manage_index_updatePs +
          "?oldPassword=" +
          oldPassword +
          "&password=" +
          password,
        {},
        true,
        ""
      ).then(function(response) {
        // 响应成功回调
        console.log(response);
        if (response) {
          if (response.success) {
            layer.closeAll();
            layer.msg(response.msg, { time: 1500, icon: 1 });
          } else {
            layer.msg(response.msg, { time: 1500, icon: 5 });
          }
        }
      });
    },
    //退出登录
    loginOut: function() {
      layer.msg("确认退出登录？", {
        time: 0, //不自动关闭
        shade: 0.5,
        btn: ["退出", "取消"],
        yes: function(index) {
          /*sessionStorageUtils.del(storageKey.sessionStorageKey.token);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.permCodes);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.schoolId);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.companyId);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.deptId);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.uploadFile.requstUrl);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.schoolMap);*/
          sessionStorage.clear();
          layer.close(index);
          //加载层-风格4
          var load = layer.msg("退出中。。。", {
            time: 0, //不自动关闭
            icon: 16,
            shade: 0.5
          });

          setTimeout(function() {
            layer.close(load);
            window.location.href = _LOGIN_PAGE;
          }, 1500);
        }
      });
    },
    //获取用户基本信息
    getUserInfo: function() {
      var that = this;
      Get(that, _HOST + _API.business_manage_sysBusiness_getUserInfo).then(
        function(response) {
          // 响应成功回调
          //console.log(response)
          if (response) {
            if (response.success) {
              //layer.msg("查询成功！");
              that.userInfo = response.data;
              console.log(that.userInfo);
              if (1 == that.userInfo.type) {
                that.iframeSrc = "home.html";
              }
            } else {
              layer.msg(response.msg, { time: 1500, icon: 5 });
            }
          }
        }
      );
    },
    //查询菜单目录
    getMenu: function(pid) {
      var that = this;
      var companyId = sessionStorageUtils.getJson(
        storageKey.sessionStorageKey.companyId
      );
      var deptId = sessionStorageUtils.getJson(
        storageKey.sessionStorageKey.deptId
      );
      Get(
        that,
        _HOST +
          _API.business_manage_index_getMenu +
          pid +
          "/" +
          companyId +
          "/" +
          deptId
      ).then(function(response) {
        // 响应成功回调
        //console.log(response)
        if (response) {
          if (response.success) {
            //layer.msg("查询成功！");
            if (0 == pid) {
              that.menuList = response.list;
              if (that.menuList.length > 0) {
                that.getMenu(that.menuList[0].id);
              }
              //ajax(that.menuList[0].id);
            } else {
              li(response.list);
            }
          } else {
            layer.msg(response.msg, { time: 1500, icon: 5 });
          }
        }
      });
    },
    //获取机构信息
    getCompanyInfo: function(companyId) {
      var that = this;
      that.deptPermList = [];
      Get(
        that,
        _HOST + _API.business_manage_index_getCompanyInfo + companyId
      ).then(function(response) {
        // 响应成功回调
        if (response) {
          if (response.success) {
            //layer.msg("查询成功！");
            if (0 == companyId) {
              that.companyList = response.data.companyMapList;
            }
            sessionStorageUtils.setJsonStr(
              storageKey.sessionStorageKey.companyId,
              companyId
            );
            that.deptPermList = response.data.deptPermList;
            console.log(that.deptPermList);
            if (0 == companyId) {
              if (that.deptPermList.length > 0) {
                for (dept of that.deptPermList) {
                  if (dept.type == 1) {
                    schoolMap.set(dept.schoolId, dept.name);
                  }
                }
                sessionStorageUtils.setJsonStr(
                  storageKey.sessionStorageKey.schoolMap,
                  MapToObj(schoolMap)
                );
                if (that.deptPermList[0].type == 1) {
                  sessionStorageUtils.setJsonStr(
                    storageKey.sessionStorageKey.schoolId,
                    that.deptPermList[0].schoolId
                  );
                } else {
                  sessionStorageUtils.setJsonStr(
                    storageKey.sessionStorageKey.schoolId,
                    ""
                  );
                }
                sessionStorageUtils.setJsonStr(
                  storageKey.sessionStorageKey.companyId,
                  that.deptPermList[0].companyId
                );
                sessionStorageUtils.setJsonStr(
                  storageKey.sessionStorageKey.deptId,
                  that.deptPermList[0].id
                );
                that.companyText = that.deptPermList[0].name;
                that.authorizedLogin(
                  that.deptPermList[0].companyId,
                  that.deptPermList[0].id
                );
              }
            } else {
              creatDeptLi(that.deptPermList);
            }
          } else {
            layer.msg(response.msg, { time: 1500, icon: 5 });
          }
        }
      });
    },
    //授权登录
    authorizedLogin: function(companyId, deptId) {
      var that = this;
      that.menuList = [];
      Get(
        that,
        _HOST +
          _API.business_manage_index_authorizedLogin +
          companyId +
          "/" +
          deptId
      ).then(function(response) {
        // 响应成功回调
        console.log(response);
        if (response) {
          if (response.success) {
            that.menuList = response.menuList;
            //console.log(that.menuList)
            if (that.menuList.length > 0) {
              that.toggleIndex = 0;
              that.getMenu(that.menuList[0].id);
            }
            sessionStorageUtils.setJsonStr(
              storageKey.sessionStorageKey.token,
              response.token
            );
            sessionStorageUtils.setJsonStr(
              storageKey.sessionStorageKey.permCodes,
              response.permCodes
            );
          } else {
            layer.msg(response.msg, { time: 1500, icon: 5 });
          }
        }
      });
    },
    toggle: function(id, index) {
      var that = this;
      that.toggleIndex = index;
      that.getMenu(id);
      //ajax(id);
    },
    changeCompany: function() {
      var that = this;
      var companyId = sessionStorageUtils.getJson(
        storageKey.sessionStorageKey.companyId
      );
      var deptId = sessionStorageUtils.getJson(
        storageKey.sessionStorageKey.deptId
      );
      /*            var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);
                        console.log(schoolMap)
                        console.log(schoolMap["6"])
                        console.log(schoolMap["7"])*/
      var htmlStr = "<div style='width: 100%;'>";

      htmlStr += "<ul class='list-group list-group-left'>";
      for (company of that.companyList) {
        htmlStr +=
          "<li onclick='companyClick(this)' data-id='" +
          company.id +
          "' class='list-group-item " +
          (company.id == companyId ? "list-group-item-active" : "") +
          "'>" +
          company.name +
          "</li>";
      }
      htmlStr += "</ul>";

      htmlStr += "<ul class='list-group list-group-right' id='deptPermList'>";
      for (var i = 0; i < that.deptPermList.length; i++) {
        htmlStr +=
          "<li onclick='deptClick(this)' data-index='" +
          i +
          "' data-id='" +
          that.deptPermList[i].id +
          "' class='list-group-item " +
          (that.deptPermList[i].id == deptId ? "list-group-item-active" : "") +
          "'>" +
          that.deptPermList[i].name +
          "</li>";
      }
      htmlStr += "</ul>";
      htmlStr += "</div>";
      //页面层
      parent.layer.open({
        title: "机构单位切换",
        type: 1,
        area: ["420px", "420px"], //宽高
        content: htmlStr
      });
    }
  }
});

function submitPWD() {
  app.submitPwd();
}

// 定时任务取得消息
var t2 = window.setInterval(function() {
  var length = app.messageList.length;
  app.messageList = [];
  app.getListToday();
  app.getBackMessage();
  setTimeout(function() {
    var length2 = app.messageList.length;
    if (length2 > length) {
      // 播放音乐
      console.log("voice");
      var audioEle = new Audio("../../../public-tools/pc/voice/new-order.mp3");
      audioEle.load();
      audioEle.play();
    }
  }, 500);
}, 32000);

/**
 * 机构点击事件
 * @param that
 */
function companyClick(that) {
  $(that)
    .siblings("li")
    .removeClass("list-group-item-active"); // 删除其他兄弟元素的样式
  $(that).addClass("list-group-item-active");
  var companyId = sessionStorageUtils.getJson(
    storageKey.sessionStorageKey.companyId
  );
  if ($(that).attr("data-id") != companyId) {
    $("#deptPermList>li").remove();
    app.getCompanyInfo($(that).attr("data-id"));
  }
}

function creatDeptLi(deptPermList) {
  var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
  var htmlStr = "";
  for (var i = 0; i < deptPermList.length; i++) {
    if (deptPermList[i].type == 1) {
      schoolMap.set(deptPermList[i].schoolId, deptPermList[i].name);
    }
    htmlStr +=
      "<li onclick='deptClick(this)' data-index='" +
      i +
      "' data-id='" +
      deptPermList[i].id +
      "' class='list-group-item " +
      (deptPermList[i].id == deptId ? "list-group-item-active" : "") +
      "'>" +
      deptPermList[i].name +
      "</li>";
  }
  $("#deptPermList").append(htmlStr);
}

/**
 * 机构单位点击事件
 * @param that
 */
function deptClick(that) {
  $(that)
    .siblings("li")
    .removeClass("list-group-item-active"); // 删除其他兄弟元素的样式
  $(that).addClass("list-group-item-active");
  var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
  if ($(that).attr("data-id") != deptId) {
    $(".J_tabCloseAll").click();
    var index = $(that).attr("data-index");
    if (app.deptPermList.length > 0) {
      if (app.deptPermList[index].type == 1) {
        sessionStorageUtils.setJsonStr(
          storageKey.sessionStorageKey.schoolId,
          app.deptPermList[index].schoolId
        );
      } else {
        sessionStorageUtils.setJsonStr(
          storageKey.sessionStorageKey.schoolId,
          ""
        );
      }
      sessionStorageUtils.setJsonStr(
        storageKey.sessionStorageKey.schoolMap,
        MapToObj(schoolMap)
      );
      sessionStorageUtils.setJsonStr(
        storageKey.sessionStorageKey.companyId,
        app.deptPermList[index].companyId
      );
      sessionStorageUtils.setJsonStr(
        storageKey.sessionStorageKey.deptId,
        app.deptPermList[index].id
      );
      $("#side-menu>li")
        .nextAll()
        .remove();
      app.companyText = app.deptPermList[index].name;
      parent.layer.closeAll();
      app.authorizedLogin(
        app.deptPermList[index].companyId,
        app.deptPermList[index].id
      );
    }
  }
}

/**
 * 动态构建权限菜单
 * @param list
 */
function li(list) {
  $("#side-menu>li")
    .nextAll()
    .remove();
  var liHtml = "";
  for (var i = 0; i < list.length; i++) {
    liHtml =
      liHtml +
      '<li><a class="' +
      (list[i].children.length > 0 ? "" : "J_menuItem") +
      '" href="' +
      (list[i].children.length > 0 ? "javascript:;" : list[i].url) +
      '" onclick="clickMenuChildren(this)"><i class="' +
      list[i].icon +
      '"></i><span class="nav-label">' +
      list[i].name +
      "</span>";
    if (list[i].children.length > 0) {
      liHtml =
        liHtml +
        '<span class="fa arrow"></span></a><ul class="nav nav-second-level collapse">';
      for (var j = 0; j < list[i].children.length; j++) {
        liHtml =
          liHtml +
          '<li><a class="J_menuItem" href="' +
          list[i].children[j].url +
          '"><i class="' +
          list[i].children[j].icon +
          '"></i>' +
          list[i].children[j].name +
          "</a></li>";
      }
      liHtml = liHtml + "</ul>";
    } else {
      liHtml = liHtml + "</a>";
    }
    liHtml = liHtml + "</li>";
  }
  $("#side-menu").append(liHtml);
  new_element = document.createElement("script");
  new_element.setAttribute("type", "text/javascript");
  new_element.setAttribute("src", "../../../public-tools/pc/js/contabs.min.js");
  document.body.appendChild(new_element);
}

/**
 * 菜单点击样式跟换
 * @param that
 */
function clickMenuChildren(that) {
  $(that)
    .parent("li")
    .siblings("li")
    .removeClass("active"); // 删除其他兄弟元素的样式
  $(that)
    .parent("li")
    .siblings("li")
    .children("ul")
    .removeClass("in"); // 删除其他兄弟元素的样式
  $(that)
    .next("ul")
    .addClass("in"); // 删除其他兄弟元素的样式
  if (
    $(that)
      .parent("li")
      .hasClass("active")
  ) {
    $(that)
      .parent("li")
      .removeClass("active");
    $(that)
      .next("ul")
      .removeClass("in"); // 删除其他兄弟元素的样式
  } else {
    $(that)
      .parent("li")
      .addClass("active");
  }
}

// 创建新Tab
function createTab(url, text) {
  var o = url,
    m = 0,
    l = text,
    k = true;
  if (o == undefined || $.trim(o).length == 0) {
    return false;
  }
  $(".J_menuTab", parent.document).each(function() {
    if ($(this).data("id") == o) {
      if (!$(this).hasClass("active")) {
        $(this)
          .addClass("active")
          .siblings(".J_menuTab")
          .removeClass("active");
        // g(this);
        $(".J_mainContent .J_iframe").each(function() {
          if ($(this).data("id") == o) {
            $(this)
              .show()
              .siblings(".J_iframe")
              .hide();
            return false;
          }
        });
        k = false;
        return false;
      } else {
        $(this).hide();
        $(".J_mainContent .J_iframe").each(function() {
          if ($(this).data("id") == o) {
            $(this).hide();
          }
        });
      }
    }
  });
  if (k) {
    var p =
      '<a href="javascript:;" class="active J_menuTab" data-id="' +
      o +
      '">' +
      l +
      ' <i class="fa fa-times-circle"></i></a>';
    $(".J_menuTab", parent.document).removeClass("active");
    var n =
      '<iframe class="J_iframe" name="iframe' +
      m +
      '" width="100%" height="100%" src="' +
      o +
      '" frameborder="0" data-id="' +
      o +
      '" seamless></iframe>';
    $(".J_mainContent", parent.document)
      .find("iframe.J_iframe")
      .hide()
      .parents(".J_mainContent")
      .append(n);
    $(".J_menuTabs .page-tabs-content", parent.document).append(p);
    // g($(".J_menuTab.active", parent.document))
  }
  return false;
}

/**
 * 备用
 * @param pid
 */
function ajax(pid) {
  var index = layer.load();
  $.ajax({
    async: true,
    url: _HOST + _API.admin_index_getMenu + pid,
    type: "get",
    dataType: "json",
    headers: {
      Authorization: sessionStorageUtils.getJson(
        storageKey.sessionStorageKey.token
      )
    },
    success: function(data) {
      layer.close(index);
      if (data.success) {
        console.log(data);
        if (0 == pid) {
          app.menuList = data.list;
          //that.getMenu(that.menuList[0].id);
          ajax(app.menuList[0].id);
        } else {
          li(data.list);
        }
      }
    }
  });
}
